import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './entities/user.entity';
import jwtConfig from '../../config/jwt.config';
import { JwtService } from '@nestjs/jwt';
import { ConfigType } from '@nestjs/config';
import * as moment from 'moment';

@Injectable()
export class UserService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @Inject(jwtConfig.KEY)
    private readonly jwtConfiguration: ConfigType<typeof jwtConfig>,
    private readonly jwtService: JwtService,
  ) {}
  // 获取所有用户数据列表(userRepository.query()方法属于typeoram)
  async findAll(page, limit): Promise<any> {
    const skip = (page - 1) * limit;
    const res = await this.userRepository.find({
      skip,
      take: limit,
    });
    const resTemp = res.map((item) => {
      return {
        ...item,
        createTime: moment(item.createTime).format('yyyy-MM-DD HH:mm:ss'),
      };
    });
    Object.assign(res, resTemp);
    const total = await this.userRepository.count();
    return {
      data: res,
      total,
      page,
      limit,
    };
  }

  // 创建
  async create(user: UserEntity): Promise<any> {
    const data = new UserEntity();
    data.name = user.name;
    data.password = user.password;
    data.userName = user.userName;
    return this.userRepository.save(data);
  }

  // 登录判断
  async login(user: UserEntity): Promise<any> {
    const res = await this.userRepository.findOne({
      where: {
        userName: user.userName,
        password: user.password,
      },
    });
    if (!res) {
      throw new Error('用户信息错误');
    }
    return true;
  }

  // 获取用户信息
  async getInfo(authorization) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [_, token] = authorization?.split(' ') ?? [];
    console.log(token);

    const payload = await this.jwtService.verifyAsync(
      token,
      this.jwtConfiguration,
    );
    const userId = payload.id;
    // 获取用户信息
    const userInfo = await this.userRepository.findOne({
      where: { id: userId },
    });
    if (!userInfo) {
      throw new Error('用户信息错误');
    }
    // 删除password
    userInfo.password = undefined;
    return userInfo;
  }
}
